package com.zrb.mobile.ui.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView.RecyclerListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.model.BaseDto;
import com.zrb.mobile.adapter.model.OwnProjectDto;
import com.zrb.mobile.adapter.model.OwnProjectDtos;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.ucenter.User_OwnProjectFragment;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

public abstract class ARefreshFragment<T extends BaseDto>  extends ABaseFragment implements  AdapterView.OnItemClickListener   {

	
	private ABaseAdapter<T> mAdapter;
	
	
	ABaseAdapter<T> getABaseAdapter() {
		return mAdapter;
	}
	
	public enum RefreshMode {
		/**
		 * 重设数据
		 */
		reset,
		/**
		 * 拉取更多
		 */
		loadmore,
		/**
		 * 刷新最新
		 */
		refresh
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/*ArrayList<T> datas = savedInstanceState == null ? new ArrayList<T>()
                                                        : (ArrayList<T>) savedInstanceState.getSerializable(SAVED_DATAS);*/
		
		ArrayList<T> datas = new ArrayList<T>();
		mAdapter = new MyBaseAdapter(datas, getActivity());
		
/*		if (savedInstanceState != null && savedInstanceState.getSerializable(SAVED_PAGING) != null) {
            mPaging = (IPaging) savedInstanceState.getSerializable(SAVED_PAGING);
		} else {
            mPaging = configPaging();
		}*/
	}
	
 
	
	@SuppressLint("NewApi")
	@Override
	void _layoutInit(LayoutInflater inflater, Bundle savedInstanceSate) {
		super._layoutInit(inflater, savedInstanceSate);
		
		if (getRefreshView() != null) {
		/*	getRefreshView().setOnScrollListener(this);
			getRefreshView().setRecyclerListener(this);*/
			
			//getRefreshView().setOnRefreshListener(this);
            getRefreshView().setOnItemClickListener(this);
		}
 
        getRefreshView().initAdapter(getAdapter());//.setAdapter(getAdapter());
		
       // onChangedByConfig(refreshConfig);
	}
 
	
	public BaseAdapter getAdapter() {
	/*	if (swingAnimAdapter != null)
			return swingAnimAdapter;*/
		
		return mAdapter;
	}
	
	
	public void notifyDataSetChanged() {
 			mAdapter.notifyDataSetChanged();
 	}
	
	public ArrayList<T> getAdapterItems() {
		return mAdapter.getDatas();
	}
	
	private int getAdapterCount() {
  		return mAdapter.getCount();
	}

	public void setAdapterItems(ArrayList<T> items) {
		mAdapter.setDatas(items);
	}
 	
	public void addItems(List<T> items,boolean isAppend) {
 		if(!isAppend) getAdapterItems().clear();
		mAdapter.addItems(items);
	}
	
	public T getLastItem(){
 		return getAdapterItems().get(getAdapterCount()-1);
	}
	
 
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

	}
	
	
	
	abstract protected ABaseAdapter.AbstractItemView<T> newItemView();
	
	//abstract public AbsListView getRefreshView();
	abstract public PullToRefreshListViewEx getRefreshView();
	
	class MyBaseAdapter extends ABaseAdapter<T> {

        public MyBaseAdapter(ArrayList<T> datas, Activity context) {
			super(datas, context);
		}

		@Override
		protected AbstractItemView<T> newItemView() {
			return ARefreshFragment.this.newItemView();
		}

	}
	
	abstract public void onRefreshViewComplete();
	
	abstract public void onHandlerResult(String resStr,RefreshMode curMode);
	
	
	RefreshMode mode;
	ZrbRestClient mZrbRestClient;// final Class<T> responseCls
	public  void LoadData(String urlParams,RefreshMode curMode,final TypeToken<List<T>> responseCls) {
		mode=curMode;
		if(null==mZrbRestClient){
			mZrbRestClient=new ZrbRestClient(this.getActivity());
			mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

					CommonUtil.showToast(arg0,ARefreshFragment.this.getActivity());
					onRefreshViewComplete();
				   if (mode==RefreshMode.loadmore)
					   getRefreshView().hideloading();
					else
						getRefreshView().onRefreshComplete(); 
 				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// loadingview.Hide();
					String results = new String(arg2);
					
					
 					onRefreshViewComplete();
 				    if (mode==RefreshMode.loadmore)
 						   getRefreshView().hideloading();
 						else
 							getRefreshView().onRefreshComplete();
					try {
						JSONObject jsonObject2 = new JSONObject(results);
						int retCode= jsonObject2.getInt("res");
						
 	 				    if(retCode==1){
	 				    	
	 				    //	onHandlerResult(jsonObject2.getString("data"),mode);
	 				    	Gson gson = new Gson(); 
	 				    	List<T> tmpdatas=gson.fromJson(jsonObject2.getString("data"), responseCls.getType());
	  				    	int size=CommonUtil.getSize(tmpdatas);
	 						if(size>0){  
	 				 			addItems(tmpdatas,mode==RefreshMode.loadmore) ;
	 				  		    notifyDataSetChanged();
	 						} 
	 						else {
	 								CommonUtil.showToast(String.format("暂无%1$s信息~~", mode==RefreshMode.refresh? "": "更多") );
	 						}
	 						//Type listType = new TypeToken<List<T>>(){}.getType();
	 				    	
	 				  /*   	Type listType = new TypeToken<List<T>>(){}.getType(); 
	 				     	
	 				    
	 				     	CommonUtil.InfoLog("data", jsonObject2.getString("data"));
	 				     	CommonUtil.InfoLog("listType", listType.toString());
	 				      	Gson gson = new Gson(); 
	 				     	List<T> users = gson.fromJson(jsonObject2.getString("data"), listType); 
	 			 	 	    int size=CommonUtil.getSize(users);
	 					    if(size>0){  
	 			 			     addItems(users,mode==RefreshMode.loadmore) ;
	 			  		         notifyDataSetChanged();
	 					     } 
	 					    else {
	 							CommonUtil.showToast(String.format("暂无%1$s信息~~", mode==RefreshMode.refresh? "": "更多") );
	 					     }*/
	/* 				    	T result = null;
//	 				    	myprojectlistAdapter.setJsonDatas(results,currentPage>1);
//	 				    	int size=myprojectlistAdapter.getCurpageSize();
							if(size>0){  
								//myprojectlistAdapter.notifyDataSetChanged();
  							} else {
 								CommonUtil.showToast(String.format("暂无%1$s信息~~", currentPage == 1 ? "": "更多") );
							}
	 				    	Gson gson = new Gson();
	 				    	result = gson.fromJson(results,responseCls);*/
	 				    	 
	 				    	//new TypeToken<List<T>>()
 	 				    	//ArrayList<T> tmpDto = gson.fromJson(results,T.class));
						} else
							CommonUtil.showToast(jsonObject2.getString("msg"));
					} catch (Exception e) {
						CommonUtil.showToast(R.string.error_serverdata_loadfail,ARefreshFragment.this.getActivity());
						 
					}
				}
			});
 		}
		mZrbRestClient.getcheckSession(urlParams);
	}

	//	Gson gson = new Gson();
	//OwnProjectDtos tmpDto = gson.fromJson(tmpDtos,OwnProjectDtos.class);
/*	public  static <T>T fromJson(String json,Class<T> classOfT){
        Gson gson=new GsonBuilder()
                .registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())
                .setDateFormat("yyyyMMddhhmmss")
                .create();
        return gson.fromJson(json, classOfT);
    }*/
	
	public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {

		Gson gson = new Gson();
		try {
			return (T) gson.fromJson(json, token.getType());
		} catch (Exception ex) {
			ex.printStackTrace();

			CommonUtil.InfoLog(json + " 无法转换为 " + token.getRawType().getName() + " 对象!", ex.getMessage());

			return null;
		}
	}

}
